package team.pra.manager.common;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局错误处理
 */
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(value = {AuthenticationException.class,RuntimeException.class})
    public Map<String, String> sendException(Exception e) {
        Map<String, String> result = new HashMap<String, String>();
        System.out.println("----global exception----");
        result.put("status", "400");
        //获取错误中中括号的内容
        String message = e.getMessage();
        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        if (message.contains("role")) {
            result.put("msg", "对不起，您没有" + msg + "角色");
        } else if (message.contains("permission")) {
            result.put("msg", "对不起，您没有" + msg + "权限");
        } else {
            result.put("msg", "功能未开发");
        }
        return result;
    }
    /*@ExceptionHandler({SQLException.class, RuntimeException.class})
    public Map<String, String> sqlException(Exception e){
        Map<String, String> result = new HashMap<String, String>();
        result.put("status", "400");
        result.put("msg","系统正在维护中。。");
        return result;
    }*/
    @ExceptionHandler(value = {Throwable.class,SQLException.class,MySQLIntegrityConstraintViolationException.class})
    public Map<String, String> sendCascadeException(Exception e) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("status", "500");
        result.put("msg","功能未开发");
        return result;
    }
}
